<?php

class Silk_Mapi_Model_Api2_Captcha_Rest extends Silk_Mapi_Model_Api2_Captcha
{
    public function _create($data)
    {
        if (isset($data['mobile']) && $data['mobile']) {
            $mobile = $data['mobile'];
            if (!preg_match("/^[1][34578][0-9]{9}$/", $mobile)) {
                $this->_critical('手机号码格式不正确！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_MOBILE_FORMAT_ERROR);
            }

            /** @var Mage_Customer_Model_Customer $customerModel */
            $customerModel = Mage::getModel('customer/customer');
            $email = "{$mobile}@hahahui.cn";
            $collection = $customerModel->getCollection()->addAttributeToFilter('email', array('eq' => $email));
            $item = $collection->getFirstItem();

            if (!$item || !$item->getId()) {
                $this->_critical('当前用户不存在！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_NOT_FOUND);
            }
            
            $captcha = Mage::helper('core')->getRandomString(6, Mage_Core_Helper_Data::CHARS_PASSWORD_DIGITS);
            /** @var Silk_Mapi_Model_Sms $sms */
            $sms = Mage::getModel('mapi/sms');
            $result = $sms->sendText($mobile, "您的验证码是 {$captcha} 请在10分钟内进行验证。");
            if ($result) {
                $cacheKey = 'CAPTCHA_'.$data['mobile'];
                $cache = Mage::app()->getCache();
                $cache->save($captcha, $cacheKey, array('QSLB_CAPTCHA'), 600);
                return array();
            } else {
                $this->_critical('验证码发送失败！', Mage_Api2_Model_Resource::ERROR_CAPTCHA_SEND_FAIL);
            }
        } else {
            $this->_critical('请输入手机号码！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_MOBILE_EMPTY);
        }
    }
}